package seven;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import com.sun.jdmk.comm.HtmlAdaptorServer;

/**
 * 用JDK jconsole来连接MBean
 * 有两种方式：
 * 一、 vm参数方式
 * 	  1、还是用第一篇的那个HelloAgent，修改HelloAgent，将第一句： MBeanServer server = MBeanServerFactory.createMBeanServer(); 
 *	    	 改为：MBeanServer server = ManagementFactory.getPlatformMBeanServer(); 
 *	  		 注：ManagementFactory的全路径为：java.lang.management.ManagementFactory 
 *	 2、修改Eclipse的run选项，把“-Dcom.sun.management.jmxremote=HelloAgent”这一句加入到run选项中 
 *	 3、运行HelloAgent，然后在Dos窗口输入“jconsole”来启到JConsole 
 *	 4、单击“连接“
 *
 * 二、RMI方式
 * 	  1、还是用第一篇的HelloAgent，加上一段代码，启动一个JMXConnectorServer服务 
 * 	  2、在Dos运行一个命令：rmiregistry 9999 
 *	  3、运行HelloAgent，然后再在dos下运行命令jconsole 输入service:jmx:rmi:///jndi/rmi://localhost:9999/server 
 *
 */
public class HelloAgent {

	public static void main(String[] args) throws Exception {
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		ObjectName helloName = new ObjectName("liuys:name=helloWorld");
		Hello hello = new Hello();
		server.registerMBean(hello, helloName);
		
		ObjectName adapterName = new ObjectName("HelloAgent:name=htmladapter,port=8082");
		HtmlAdaptorServer adaptor = new HtmlAdaptorServer();
		server.registerMBean(adaptor, adapterName);
		
		adaptor.start();
		System.out.println("start.....................");
		
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
		JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
		cs.start();
		System.out.println("rmi start.................");
	}
}
